﻿<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/common/header.jsp"%>
<script type="text/javascript" src="../../js/deptSingleSelect.js"></script>
<script type="text/javascript" src="../../js/roleSingleSelect.js"></script>
<a href="" title="短信发送"></a>
<script type="text/javascript">

Ext.onReady(function(){
    Ext.BLANK_IMAGE_URL = ' ../../js/ext/images/default/s.gif'; 
    // ---------------------- Global vars and functions------------------------------
    Ext.SERVER = '<c:url value="/"/>';
    //depttree选中节点列表
    var deptList = [];
    //roletree选中节点列表
    var roleList = [];
   //-------------验证-------------------
        img1=function(){
	document.getElementById('image').src+="?";
	document.getElementById('captcha_response').value="";
  };
  
   var imagePreview=new Ext.Panel({
    id: 'imagePreview',
    name: 'imageUrl',
   	fieldLabel: '验证码',
   	layout:'form',
    autoWidth: true, //自动调整图片宽度  
    height: 30, //图片高度  
    qtip: '看不清楚，换一张！',
    html:"<a href='#'  onclick='img1()'>看不清,换一张</a>",
    items:[
    {
	  	xtype:'box',
	  	id:'image',
	  	name:'image',
	  	autoEl: {  
	        tag: 'img',    //指定为img标签  
	        src: 'captcha.do'    //指定url路径  
	    }
    }
    ]
    });
    //--------------- checkbox选择模型 -------------------  
    var sm3 = new Ext.grid.CheckboxSelectionModel({ checkOnly: true });
    //--------------- checkbox选择模型 -------------------  
    var sm2 = new Ext.grid.CheckboxSelectionModel({ checkOnly: true });
     //--------------- checkbox选择模型 -------------------  
    var sm1 = new Ext.grid.CheckboxSelectionModel({ checkOnly: true });
    //--------------- checkbox选择模型 -------------------  
    var sm4 = new Ext.grid.CheckboxSelectionModel({ checkOnly: true });
    // --------------- grid 全清功能 -------------------
    Ext.grid.GridPanel.prototype.unSelectAll = function(){
        var view = this.getView();
        var sm = this.getSelectionModel();
        if(sm){
            sm.clearSelections();
            var hd = Ext.fly(view.innerHd);
            var c = hd.query('.x-grid3-hd-checker-on');
            if(c && c.length>0){
                Ext.fly(c[0]).removeClass('x-grid3-hd-checker-on')
            }
        }
    };
    Ext.QuickTips.init();
    Ext.override(Ext.form.Field, 
    {   afterRender : Ext.form.Field.prototype.afterRender.createSequence(function()
        {
            var qt = this.qtip;
            if (qt)
            {   Ext.QuickTips.register({
                target:  this,
                title: '',
                css : 'background:#ff0000;',
                text: qt,
                enabled: true,
                showDelay: 20
                });
            }
        })
    });
    // ------------ 得到url参数-------------------------   
    function GetUrlParms()    
    {
         var args=new Object();   
         var query=location.search.substring(1);//获取查询串   
         var pairs=query.split("&");//在逗号处断开   
         for(var    i=0;i<pairs.length;i++)   
         {   
             var pos=pairs[i].indexOf('=');//查找name=value   
             if(pos==-1)   continue;//如果没有找到就跳过   
             var argname=pairs[i].substring(0,pos);//提取name   
             var value=pairs[i].substring(pos+1);//提取value   
             args[argname]=unescape(value);//存为属性   
        }
         return args;
    }
    
    // ---------------------- North: Query Zone -------------------------
     // 应用系统下拉选项框
    Ext.applicationComBox = new Ext.form.ComboBox({       
        region: 'north',
        name: 'appList',
        hiddenName: 'appList',
        fieldLabel: '请选择系统',
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'remote',
        store: new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: Ext.SERVER+'role/queryAppList.do'
            }),
            reader: new Ext.data.JsonReader({
                root: 'data',
                id: 'key'
                }, 
                ['key', 'value']
            )
        }),
        valueField: 'key',
        displayField: 'value',
        listeners: {
            select: function(combo,record,index){   
                 Ext.applicationID = Ext.applicationComBox.getValue();             
                 // 系统选择改变，重新加载角色树               
                 roleMentTree.root.reload();                
                 roleMentTree.root.select();                              
             }
        }
    });
    
    // ---------------------- West: Role Tree   -------------------------
    var params = GetUrlParms();
	// --------------- TreeCheckNodeUI -------------------
	Ext.ux.TreeCheckNodeUI = function() {
		    // 多选: 'multiple'(默认)
		    // 单选: 'single'
		    // 级联多选: 'cascade'(同时选父和子);'parentCascade'(选父);'childCascade'(选子)
		    this.checkModel = 'cascade';
		    // only leaf can checked
		    this.onlyLeafCheckable = false;
            Ext.ux.TreeCheckNodeUI.superclass.constructor.apply(this, arguments);
    };
    Ext.extend(Ext.ux.TreeCheckNodeUI, Ext.tree.TreeNodeUI, {
        renderElements : function(n, a, targetNode, bulkRender) {
            var tree = n.getOwnerTree();
            this.checkModel = tree.checkModel || this.checkModel;
            this.onlyLeafCheckable = tree.onlyLeafCheckable || false;
            // add some indent caching, this helps performance when
            // rendering a large tree
            this.indentMarkup = n.parentNode ? n.parentNode.ui
                    .getChildIndent() : '';
            // var cb = typeof a.checked == 'boolean';
            var images = '../../js/ext/images/' + n.attributes.checked + '.gif';
            var cb = (!this.onlyLeafCheckable || a.leaf);
            var href = a.href ? a.href : Ext.isGecko ? "" : "#";
            var buf = ['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ', a.cls,'" unselectable="on">',
            '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
            '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow" />',
            cb ? ('<img class="x-tree-node-cb" src="../../js/ext/images/' + (a.checked ? 'all.gif"/>' : 'none.gif"/>')) : '',
            '<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ',
             a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '><span unselectable="on">',n.text,"</span></a></div>",
            '<ul class="x-tree-node-ct" style="display:none;"></ul>',
            "</li>"].join('');
           
            var nel;
            if (bulkRender !== true && n.nextSibling
                    && (nel = n.nextSibling.ui.getEl())) {
                this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel,
                        buf);
            } else {
                this.wrap = Ext.DomHelper.insertHtml("beforeEnd",
                        targetNode, buf);
            }
            this.elNode = this.wrap.childNodes[0];
            this.ctNode = this.wrap.childNodes[1];
            var cs = this.elNode.childNodes;
            this.indentNode = cs[0];
            this.ecNode = cs[1];
            var index = 2;
            if (cb) {
                this.checkbox = cs[2];
                Ext.fly(this.checkbox).on('click',
                        this.onCheck.createDelegate(this, [null]));
                index++;
            }
            this.anchor = cs[index];
            this.textNode = cs[index].firstChild;
        },
        // private
        onCheck : function() {
            this.check(this.toggleCheck(this.node.attributes.checked));
        },
        // private
	    onDblClick : function(e){
	        e.preventDefault();	       
	    },
        
        // private
        check : function(checked){
            var n = this.node;
	      var tree = n.getOwnerTree();
	      this.checkModel = tree.checkModel || this.checkModel;
	      
	      if( checked === null ) {
	       checked = this.checkbox.checked;
	      } else {
	       this.checkbox.checked = checked;
	      }
	      
	      n.attributes.checked = checked;
	      tree.fireEvent('check', n, checked);
	      this.setNodeIcon(n);
	      if(this.checkModel == 'single'){
	       var checkedNodes = tree.getChecked();
	       for(var i=0;i<checkedNodes.length;i++){
	        var node = checkedNodes[i];
	        if(node.id != n.id){
	         node.getUI().checkbox.checked = false;
	         node.attributes.checked = false;
	         tree.fireEvent('check', node, false);
	        }
	       }
	      } else if(!this.onlyLeafCheckable){
	      if(this.checkModel == 'cascade' || this.checkModel == 'childCascade'){
            if( !n.expanded && !n.childrenRendered ) {
             n.expand(false,false,this.childCheck);
            }else {
             this.childCheck(n); 
            }
           }
	       if(this.checkModel == 'cascade' || this.checkModel == 'parentCascade'){
	        var parentNode = n.parentNode;
	        if(parentNode !== null) {
	         this.parentCheck(parentNode,checked);

	        }
	       }
	      }
	     },
        // private
	     parentCheck : function(node, checked){
	       var checkbox = node.getUI().checkbox;
	      if(typeof checkbox == 'undefined')return ;
	      if(checked === checkbox.checked)return;
	      if(!checked && this.childHasChecked(node))return;
                    var part = false;
                    var sel = 0;
                    var selType  = 'part';
                    Ext.each(node.childNodes, function(child) {
                                if (child.attributes.checked == 'all')
                                    sel++;
                                else if (child.attributes.checked == 'part') {
                                    part = true;
                                    return false;
                                }
                            });
                    if (part)
                    {
                        node.attributes.checked = 'part';
                        checkbox.checked = 'part';
                        selType  = 'part';
                    }else {
                        if (sel == node.childNodes.length) {
                            checkbox.checked = 'all';
                            node.attributes.checked = 'all';
                            selType  = 'part';
                        } else if (sel == 0) {
                            node.attributes.checked = 'none';
                            checkbox.checked = 'none';
                            selType  = 'part';
                        } else {
                            node.attributes.checked = 'part';
                            checkbox.checked = 'part';
                            selType  = 'part';
                        }
                    }
                    
                     this.setNodeIcon(node);
                     var parentNode = node.parentNode;
				      if( parentNode !== null){
				       this.parentCheck(parentNode,checked);
				      }
            },
	     
	     // private
	     childHasChecked : function(node){
	      var childNodes = node.childNodes;
	      if(childNodes || childNodes.length>0){
	       for(var i=0;i<childNodes.length;i++){
	        if(childNodes[i].getUI().checkbox.checked)
	         return true;
	       }
	      }
	      return false;
	     },
        setNodeIcon : function(n) {
            if (n.getUI() && n.getUI().checkbox)
                n.getUI().checkbox.src = '<c:url value="../../js/ext/images/'
                        + n.attributes.checked + '.gif"/>';
            //将tree选取的值保存在全局变量valueList中
            departListSave(n);
        },
        // private
        childCheck : function(node){
	      var a = node.attributes;
	      if(!a.leaf) {
	       var cs = node.childNodes;
	       var csui;
	       for(var i = 0; i < cs.length; i++) {
	        csui = cs[i].getUI();
            csui.check(a.checked);
	       }
	      }
	     },
        toggleCheck : function(value) {
            var cb = this.checkbox;
            if(cb){
                var checked = (value === undefined ? !cb.checked : value);
                this.check(checked);
            }
            return (value == 'all' || value == 'part') ? 'none' : 'all';
        }
    });
	
	function checkAllOrNone(node, checked) {          
        node.attributes.checked = checked;     
        node.eachChild(function(child) {     
            child.ui.toggleCheck(checked);     
            child.attributes.checked = checked;     
            child.fireEvent('checkchange', child, checked);     
        }); 
        
        storeLoad();    
    };

    //将tree选取的值保存在全局变量valueList中
    function departListSave (node){
        var a = node.attributes;
        var nodeValue = node.id;
        if(a.tree_id == "dept"){
	        var test = deptList.indexOf(nodeValue);
	        if (test == -1 && node.attributes.checked == "all") {
	            deptList.push(nodeValue)
	        }
	        if (test != -1 && node.attributes.checked == "none") {
	            deptList.remove(nodeValue);
	        }
        }
        else{
	        var test = roleList.indexOf(nodeValue);
	        if (test == -1 && node.attributes.checked == "all") {
	            roleList.push(nodeValue)
	        }
	        if (test != -1 && node.attributes.checked == "none") {
	            roleList.remove(nodeValue);
	        }
        }
    };
    
    
    // --------------- form and window --------------------
    var detailForm = new Ext.form.FormPanel({
        bodyStyle: 'padding:5px',
        title: '短信内容',
        frame: true,
        layout: 'fit',
        labelWidth : 80, 
        items: [{
             layout: 'form',
             frame:true,
             items: [
             		{			           
			            xtype:'label',
			            text: 'lengths:',
				   		id:'msg-lengths'
			        },
             		new  Ext.form.TextArea({    //TextArea
                          fieldLabel:'短信正文*',
                          name:'userNotes',
                          allowBlank: false,
                          qtip: '填写短信正文，注意：正文如果超过60个字，将作为两条短信发送！',
                          height:60,
                          width: 880,
                          id: 'userNotes',
                          enableKeyEvents:true,
                          listeners :{
							render: function( self ){
								var l = Ext.get('msg-lengths');
								l.dom.innerHTML = ' 已输入字数:'+self.getValue().length+
									' ；将当成 ' + (Math.ceil(self.getValue().length/60)) + ' 条短信发送';
								
							},
							keyup:function(self, e){		
								var l = Ext.get('msg-lengths');
								l.dom.innerHTML = ' 已输入字数:'+self.getValue().length+
									' ；将当成 ' + (Math.ceil(self.getValue().length/60)) + ' 条短信发送';
							}
						    }
                      }),{
                         name: 'userRealName',
                         fieldLabel: '签名',
                         readOnly: true,
                         xtype: 'textfield',
                         qtip: '将作为短信签名发送！',
                         width: 180,
                         msgTarget: 'side'
                     },
                     imagePreview,
                     {
                         name: 'captcha_response',
                         id:'captcha_response',
                         fieldLabel: '请输入验证码',
                         xtype: 'textfield',
                         allowBlank: false,
                         width: 180,
                         msgTarget: 'side'
                     },
					 new  Ext.form.Label({
							html:'短信使用说明：<br>  '
								+'&nbsp;&nbsp;&nbsp;&nbsp;1、您可以为常用联系人建立分组，'
								+'并通过联系人分组选择联系人，也可以直接通过添加收信人添加；<br>'
								+'&nbsp;&nbsp;&nbsp;&nbsp;2、当您选择一个或几个分组过后，还可以通过添加收信人继续添加；<br>'
								+'&nbsp;&nbsp;&nbsp;&nbsp;3、此短信平台每60个字符将计作一条短信，短信末尾将签上您的姓名；<br>'
								+'&nbsp;&nbsp;&nbsp;&nbsp;4、此短信平台暂时未开通联通方面服务。'
						})
					 ]
        }],
        buttons: [
            {
                text: '发送',
                handler: function(){
                    var idList = [];//用户id串
                    var mobileList = [];//用户电话号码串
                    var records = userGrid.getStore().getRange(0,userGrid.getStore().getCount());
		            for(var i = 0, len = records.length; i < len; i ++) {
		                idList.push(records[i].data.id);
		                mobileList.push(records[i].data.userMobile+';'+records[i].data.id);
		            }
                    if(detailForm.getForm().isValid()){
                        detailForm.getForm().submit({
                            url: '<c:url value="/sms/smsSend.do" />',
                            waitTitle: '请等待',
                            params: {
			                   // userIds: idList,
			                   userMobiles: mobileList
			                  //userIds: mobileList,
			                },
                            waitMsg: '正在发送短信中...',
                            timeout: 10,
                            success: function(form, action){
                                function ok(){
                                	img1();
                                    store.removeAll();
                                }
                                Ext.Msg.alert('提示', '发送成功！', ok);
                            },
						    failure: function(aForm,aAction) {
						    text = aAction.response.responseText;
                             json = Ext.decode(text);
						       Ext.Msg.alert('提示',json.message,img1);
						    }
                        });
                    }
                }
            }
        ]
    });
    var selectForm_userType = new Ext.form.ComboBox({
        name: 'userType',
        hiddenName: 'userType',
        fieldLabel: '用户类型',
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 'key',
            fields: [ 'key', 'value'],
            data: [
                [ '0', '普通教师'],
                [ '1', '管理员'],
                [ '2', '学校领导'],
                [ '3', '部门领导'],
                [ '5', '学生']
            ]
        }),
        valueField: 'key',
        displayField: 'value'
    });
    
    // --------------- form and window --------------------
    var selectForm = new Ext.form.FormPanel({
        bodyStyle: 'padding:5px',
        title: '过滤条件——为保证筛选的速度，请先设定过滤条件！',
        frame: true,
        layout: 'fit',
        items: [{
             layout: 'form',
             frame:true,
             items: [new  Ext.form.TextArea({    //TextArea
                          fieldLabel:'用户登录名',
                          name:'userLoginId',
                          height:40,
                          width: 164,
                          qtip: '可以同时输入多个登录名过滤，以半角"，"号分隔！',
                          id: 'userLoginId'
                      }),
                      new  Ext.form.TextArea({    //TextArea
                          fieldLabel:'姓名',
                          name:'userRealName',
                          height:40,
                          width: 164,
                          qtip: '可以同时输入多个姓名过滤，以半角"，"号分隔！',
                          id: 'userRealName'
                      }),
					  selectForm_userType,
					 {
					      baseCls: 'x-plain',
					      xtype: 'panel',
					      layout: 'table',
					      fieldLabel: '有无电话号码',
					      defaultType: 'radio',
					      isFormField: true,
					      items: [{
					       name: 'hasPhone',
					       boxLabel: '有',
						   checked:'true',
					       inputValue: 'yes'
					      },{
					       name: 'hasPhone',
					       boxLabel: '无',
					       inputValue: 'no'					
					     }]
					},
					{
					      baseCls: 'x-plain',
					      xtype: 'panel',
					      layout: 'table',
					      fieldLabel: '号码类型',
					      defaultType: 'checkbox',
					      isFormField: true,
					      items: [{
					       name: 'phoneType',
					       boxLabel: '移动',
						   checked:'true',
					       inputValue:'yidong'
					      },{
					       name: 'phoneType',
					       boxLabel: '联通',
						   checked:'true',
					       inputValue:'liantong'		
					     },{
					       name: 'phoneType',
					       boxLabel: '电信',
						   checked:'true',
					       inputValue:'dianxin'				
					     }]
					}
					]
        }],
        buttons: [
            {
                text: '点此过滤',
                handler: function(){
                    storeLoad();
                }
            }
        ]
    });
    
    // --------------- tree --------------------
    departMentTree = new Ext.tree.TreePanel({ 
                region:'west',                                         
                id:'im-tree',                        
                rootVisible:false,
                title: '部门筛选条件',
                lines:false,
                autoScroll:true,
                autoHeight:false, 
                layout: 'fit',
                height:200,
                animate: false,
                curNode: 'undefinded',  
                isDoubleClick: false,                   
                root:new Ext.tree.AsyncTreeNode({
                    id : '100000000000',
                    text: '重庆邮电大学',
                    checked:false
                }),
                loader:new Ext.tree.TreeLoader({                            
                    
					url : '<c:url value="/message/expendDepartMentTree.do" />',
                    baseAttrs: { uiProvider: Ext.ux.TreeCheckNodeUI } //添加 uiProvider 属性
                }),
		        listeners: {
		            click: function(node){
		            }
		        },
                tbar:[{
                     tooltip:'全选',
                     icon:'<c:url value="/images/all.jpg"/>',
                     cls:'x-btn-icon',
                     handler:function(){
                      var rootNode = Ext.getCmp('im-tree').getRootNode();                           
                      checkAllOrNone(rootNode,'all');

				                   }
				               },
				     '全选','-',{
				      icon:'<c:url value="/images/none.jpg"/>',
				      cls:'x-btn-icon',
				      tooltip:'全不选',
				      handler:function(){
				       var rootNode = Ext.getCmp('im-tree').getRootNode();
				       checkAllOrNone(rootNode,'none');
				      }
				     },
				     '全不选','-', {
				      icon:'<c:url value="/images/refresh.jpg"/>',
				      cls:'x-btn-icon',
				      tooltip:'刷新',
				      handler:function(){
				       var tree = Ext.getCmp('im-tree');
				       tree.body.mask('数据加载中……', 'x-mask-loading');
				       deptList.length = 0;
				       tree.root.reload();
				       tree.root.collapse(true, false);
				       tree.root.expand(false,false,function(){ 
				                           tree.body.unmask();//全部展开之后让蒙版消失  
				        }); 
				      }
				     },'刷新'],        
				listeners: {
				    click: function(node) {
				        this.curNode = node;                           
                            // 显示当前部门下的用户列表grid
                                 storeLoad();
				    }
				}  
	                                 
              
    }) 
    

// --------------- tree --------------------
    roleMentTree = new Ext.tree.TreePanel({ 
                region:'west',                                         
                id:'rm-tree',                        
                rootVisible:false,
                lines:false,
                autoScroll:true,
                autoHeight:false, 
                layout: 'fit',
                height:148,
                animate: false,
                curNode: 'undefinded',  
                isDoubleClick: false,                   
                root:new Ext.tree.AsyncTreeNode({
                    id : '-1',
                    text: '角色树' 
                }),
                loader:new Ext.tree.TreeLoader({                            
                    url : Ext.SERVER+'role/expendRoleTreeNode.do',
                    baseAttrs: { uiProvider: Ext.ux.TreeCheckNodeUI } //添加 uiProvider 属性
                }),
                listeners: {
                    click: function(n) {
                            roleMentTree.curNode = n;                          
                            // 显示当前角色下的用户列表grid
                            if(n.attributes.id!=-1) {
	                             storeLoad();
                            }
                        },
                    beforeload: function(node){
                            if(Ext.applicationID == undefined){
                               // console.log('applicationID:=unefined');
                                return false;
                            }
                            // 角色树需要应用程序ID作为参数         
                            roleMentTree.loader.baseParams.applicationID = Ext.applicationID;                        
                        }
                }
    }) 
    

// ---------------grid store -------------------

    var store = new Ext.data.JsonStore({
        url: '<c:url value="/user/userList.do" />',
        root: 'data',
        totalProperty: 'totalCount',
        idProperty: 'id',
        autoDestroy: true,
        listeners :{  
            beforeload :{  
                fn : function(store){  
                    Ext.apply(store.baseParams, selectForm.getForm().getValues());   
                }  
            }  
        },
        fields: [
            { name: 'id' },
            { name: 'loginId' },
            { name: 'userMobile' },
            { name: 'userRealName' },
            { name: 'e2qSmDepartment' },
            { name: 'e2qSmDepartmentName' }
        ]
    });

// ---------------userGrid store -------------------
    var userStore = new Ext.data.JsonStore({
        url: '<c:url value="/sms/groupUsers.do" />',
        root: 'data',
        totalProperty: 'totalCount',
        idProperty: 'id',
        autoDestroy: true,
        fields: [
       		{ name:'id'},
           	{ name: 'loginId' },
          	{ name: 'userMobile' },
            { name: 'userRealName' },
            { name: 'e2qSmDepartment' },
            { name: 'e2qSmDepartmentName' }
        ]
    });

    // ---------------groupGrid store -------------------
    var groupStore = new Ext.data.JsonStore({
       url: '<c:url value="/sms/groupList.do" />',
        root: 'data',
        totalProperty: 'totalCount',
        idProperty: 'id',
        autoDestroy: true,
       
        fields: [
            { name: 'id' },
            { name: 'ucgName' },
            { name: 'ucgValue' },
            { name: 'ucgNotes' },
            { name: 'ucgState' }
        ]
    });
    
    // ---------------groupUser grid store -------------------

    var groupUserStore = new Ext.data.JsonStore({
        url: '<c:url value="/sms/groupUsers.do" />',
        root: 'data',
        totalProperty: 'totalCount',
        idProperty: 'id',
        autoDestroy: true,
       
        fields: [
            { name: 'id' },
            { name: 'loginId' },
            { name: 'userMobile' },
            { name: 'userRealName' },
            { name: 'e2qSmDepartment' },
            { name: 'e2qSmDepartmentName' }
        ]
    });
    
    
    
    // --------------- grid actions -----------------

    var gridAddAction = new Ext.Action({
        text: '添加收信人',
        iconCls: 'btn_select',
        scale: 'small',
        disabled: false,
        handler: function(){
            userGridWindow.show();
            userGridWindow.gridFlag = '1';
            departMentTree.root.reload();
		    selectForm.getForm().reset();
		    roleMentTree.root.reload();
		    grid.getStore().removeAll();
        }
    });
    
    var gridDelAction = new Ext.Action({
        text: '删除收信人',
        iconCls: 'btn_del',
        scale: 'small',
        disabled: false,
        handler: function(){
          Ext.Msg.confirm('删除确认', '是否删除选择的记录?', function(aButton){
                    if (aButton == 'yes'){
            var records = userGrid.getSelectionModel().getSelections();
            for(var i = 0, len = records.length; i < len; i ++) {
                        userStore.remove(userStore.getById(records[i].data.id));
            }
            }
            })
        }
    });
    
    var gridSelectAction = new Ext.Action({
        text: '确定',
        iconCls: 'btn_select',
        scale: 'small',
        disabled: true,
        handler: function(){
            userGridWindow.hide();
            var records = grid.getSelectionModel().getSelections();
            if ( records ){
                 if ( userGridWindow.gridFlag == '1' ){
	                 userStore.add(records);
	            } else{
	                 groupUserStore.add(records);
                } 
            }   
        }
    });

    var gridDeleteAction = new Ext.Action({
        text: '移出',
        iconCls: 'btn_del',
        scale: 'small',
        disabled: true,
        handler: function(){
                       var records = userGrid.getSelectionModel().getSelections();
            for(var i = 0, len = records.length; i < len; i ++) {
                        userStore.remove(records[i]);
            } 
        }
    });
    var groupGridAddAction = new Ext.Action({
        text: '添加分组',
        iconCls: 'btn_select',
        scale: 'small',
        disabled: false,
        handler: function(){
            groupGridWindow.show();
        }
    });
    var groupGridEditAction = new Ext.Action({
        text: '编辑分组',
        iconCls: 'btn_select',
        scale: 'small',
        disabled: false,
        handler: function(){            
             var record = groupGrid.getSelectionModel().getSelected();
            if(record != null){
                groupGridWindow.show();
                groupForm.getForm().loadRecord(record);   
                groupUserStore.on('beforeload', function(groupUserStore,options)
				{
					var new_params={id: record.data.id};
					Ext.apply(options.params,new_params);
				});  
				groupUserStore.removeAll();
                groupUserStore.load();
             }
        }
    });
    var groupGridDelAction = new Ext.Action({
        text: '删除分组',
        iconCls: 'btn_del',
        scale: 'small',
        disabled: false,
        handler: function(){
        	var ids='';
            var records = groupGrid.getSelectionModel().getSelections();
            for(var i = 0, len = records.length; i < len; i ++) {
                        ids=ids+records[i].data.id;
            }
            Ext.Msg.confirm('删除确认', '是否删除选择的记录?', function(aButton){
                    if (aButton == 'yes'){
             Ext.Ajax.request({
                url: '<c:url value="/sms/delGroup.do" />',
                params: {
                    ids: ids
                },
                success: function(response, opts){
                    groupStore.reload({callback: groupGridChangeAction});
                    Ext.Msg.alert('提示', '操作成功。');
                },
                failure: function(response, opts){
                    Ext.Msg.alert('提示', '保存请求失败！');
                }
            })
            }
            })
        }
    });
    
    var groupUserGridAddAction = new Ext.Action({
        text: '添加成员',
        iconCls: 'btn_select',
        scale: 'small',
        disabled: false,
        handler: function(){
            userGridWindow.show();
            userGridWindow.gridFlag = '2';
            departMentTree.root.reload();
		    selectForm.getForm().reset();
		    roleMentTree.root.reload();
		    grid.getStore().removeAll();
        }
    });
    
    var groupUserGridDelAction = new Ext.Action({
        text: '删除成员',
        iconCls: 'btn_del',
        scale: 'small',
        disabled: false,
        handler: function(){
        Ext.Msg.confirm('删除确认', '是否删除选择的记录?', function(aButton){
                    if (aButton == 'yes'){
            var records = groupUserGrid.getSelectionModel().getSelections();
            for(var i = 0, len = records.length; i < len; i ++) {
                        groupUserStore.remove(records[i]);
            }
            }
            })
           
        }
    });

    function gridUpdateAction (){
            if(grid.getStore().getCount() > 0){
                gridSelectAction.enable();
            }else{
                gridSelectAction.disable();
            }
    };
    
    function userGridUpdateAction (){
            if(userGrid.getSelectionModel().hasSelection() == null || userGrid.getSelectionModel().hasSelection() === false){
                gridDelAction.disable();
            }else{
                gridDelAction.enable();
            }
    };
    function groupGridChangeAction (){
            if(groupGrid.getSelectionModel().hasSelection() == null || groupGrid.getSelectionModel().hasSelection() === false){
                groupGridDelAction.disable();
            }else{
                groupGridDelAction.enable();
            }
            if(groupGrid.getSelectionModel().hasSelection() == null || groupGrid.getSelectionModel().hasSelection() === false || groupGrid.getSelectionModel().getSelections().length>1){
                groupGridEditAction.disable();
            }else{
                groupGridEditAction.enable();
            }
            var id = ''
            var records = groupGrid.getSelectionModel().getSelections();
            for(var i = 0, len = records.length; i < len; i ++) {
                id = id + records[i].data.id + ',';
            }
            
            userStore.on('beforeload', function(userStore,options)
				{
					var new_params={id:id};
					Ext.apply(options.params,new_params);
				}); 
            userStore.load();

	        

            
    };
    
    function storeLoad (){
        store.removeAll();
        store.load({
	        params:{start:0, limit:10, roleSels:roleList, dptSels:deptList},
	        waitMsg: 'loading...',
	        callback: gridUpdateAction,
	        failure: function() {
	            Ext.Msg.alert('提示', '读取数据失败！');
	        }
	    });
    }; 
    function groupStoreLoad (){
        groupStore.removeAll();
        groupStore.load({callback: groupGridChangeAction});
    };

    // --------------- grid --------------------

    var grid = new Ext.grid.GridPanel({
        region:'center',
        store: store,
        title: '发送到',
        height:252,
        width: 334,
        trackMouseOver: false,
        disableSelection: false,
        loadMask: true,
        enableColumnHide: false,
        sm : sm3,
        viewConfig: {
            forceFit: true
        },
        columns: [
            sm3,
            {
                header: '编号',
                hidden: true,
                sortable: true,
                dataIndex: 'id'
            },
             {
                header: '登录Id',
                hidden: true,
                sortable: true,
                dataIndex: 'loginId'
            },
            {
                header: '电话号码',
                hidden: true,
                sortable: true,
                dataIndex: 'userMobile'
            },
            {
                header: '姓名',
                sortable: true,
                dataIndex: 'userRealName'
            },
            {
                header: '所在部门id',
                hidden: true,
                sortable: true,
                dataIndex: 'e2qSmDepartment'
            },
            {
                header: '所在部门',
                sortable: true,
                dataIndex: 'e2qSmDepartmentName'
            }
        ],
        bbar: [
			 new Ext.Toolbar.Fill(),
            gridSelectAction
        ]   
    });

    var userGrid = new Ext.grid.GridPanel({
        region:'center',
        store: userStore,
        title: '发送到',
        height:318,
        width: 1100,
        trackMouseOver: false,
        disableSelection: false,
        loadMask: true,
        enableColumnHide: false,
        sm : sm1,
        viewConfig: {
            forceFit: true
        },
        columns: [
            sm1,
            {
                header: '编号',
                hidden: true,
                sortable: true,
                dataIndex: 'id'
            },
            {
                header: '电话号码',
                hidden: true,
                sortable: true,
                dataIndex: 'userMobile'
            },
            {
                header: '姓名',
                sortable: true,
                dataIndex: 'userRealName'
            },
            {
                header: '所在部门id',
                hidden: true,
                sortable: true,
                dataIndex: 'e2qSmDepartment'
            },
            {
                header: '所在部门',
                sortable: true,
                dataIndex: 'e2qSmDepartmentName'
            }
        ],
        tbar: [
            gridAddAction,
            gridDelAction
        ]   
    });
    
    var groupGrid = new Ext.grid.GridPanel({
        region:'center',
        store: groupStore,
        title: '联系人分组',
        height:318,
        width: 270,
        trackMouseOver: false,
        disableSelection: false,
        loadMask: true,
        enableColumnHide: false,
        sm : sm4,
        viewConfig: {
            forceFit: true
        },
        
        columns: [
        	sm4,
            {
                header: '编号',
                hidden: true,
                sortable: true,
                dataIndex: 'id'
            },
            {
                header: '分组名',
                sortable: true,
                dataIndex: 'ucgName'
            }
        ],
        tbar: [
            groupGridAddAction,
            groupGridEditAction,
            groupGridDelAction
        ]   
    });
    
     var groupUserGrid = new Ext.grid.GridPanel({
        region:'center',
        store: groupUserStore,
        title: '分组成员',
        height:367,
        trackMouseOver: false,
        disableSelection: false,
        loadMask: true,
        enableColumnHide: false,
        sm : sm2,
        viewConfig: {
            forceFit: true
        },
        columns: [
            sm2,
            {
                header: '编号',
                hidden: true,
                sortable: true,
                dataIndex: 'id'
            },
            {
                header: '登录ID',
                hidden: true,
                sortable: true,
                dataIndex: 'loginId'
            },
            {
                header: '电话号码',
                hidden: true,
                sortable: true,
                dataIndex: 'userMobile'
            },
            {
                header: '姓名',
                sortable: true,
                dataIndex: 'userRealName'
            },
            {
                header: '所在部门id',
                hidden: true,
                sortable: true,
                dataIndex: 'e2qSmDepartment'
            },
            {
                header: '所在部门',
                sortable: true,
                dataIndex: 'e2qSmDepartmentName'
            }
        ],
        tbar: [
            groupUserGridAddAction,
            groupUserGridDelAction
        ]   
    });
    
    var userGridWindow = new Ext.Window({
        width: 700,
        height: 510,
        title: '选择用户',
        modal: true,
        layout: 'fit',
        plain: true,
        gridFlag:'undefined',
        bodyStyle: 'padding:5px;',
        buttonAlign: 'center',
        items: [{
                        layout: 'form',
                        items: [{
                                layout: 'column',
                                items: [
                                        {
                                            columnWidth: .5,
                                            layout: 'form',
                                            items: [
                                               departMentTree,
                                               selectForm
                                            ]
                                        },
                                        {
                                            columnWidth: .5,
                                            layout: 'form',
                                            items: [
                                            new Ext.Panel({
                                                region:'north',
                                                collapsible: true,
                                                title: '角色筛选条件',
                                                height: 50,
                                                tbar: ['请选择角色:',Ext.applicationComBox,'-']
                                            }),
                                                roleMentTree,
                                                grid
                                            ]
                                        }
                                    ]
                            }
                        ]
                    }
                    ],
        closeAction: 'hide'
    });
    
     var groupForm = new Ext.form.FormPanel({
        title:'分组信息',
        id: 'gForm',
        bodyStyle: 'padding:5px',
        buttonAlign:'center',
        frame: true,
        items: [{
                        		 			name: 'ucgName',
                                            xtype: 'textfield',
                                            labelWidth: 100,
                                            width: 180,
                                            msgTarget: 'side',
                                            fieldLabel: '分组名'
                        		},
                        		{
                        		 			name: 'id',
                        		 			xtype: 'textfield',
											inputType: 'hidden',
                                            msgTarget: 'side',
                                            fieldLabel: '分组id'
                        		},
                        		 new  Ext.form.TextArea(  {    //TextArea
		                            fieldLabel:'备注',
		                            name:'ucgNotes',
		                            width: 500,
		                            height: 90,
		                            id: 'ucgNotes'
		                      	  })],
		 buttons: [
            {
                text: '保存',
                handler: function(){
                    //将全局变量valueList的值保存在form的dptSels变量中传回后台
                   var loginIds='';
                   for (var i = 0; i < groupUserStore.getCount(); i++) {   
					    var record = groupUserStore.getAt(i);   
					    loginIds=loginIds+record.get('loginId')+',';
					}  
					
		            if(groupForm.getForm().isValid()){
                        groupForm.getForm().submit({
                            url: '<c:url value="/sms/saveOrUpdateGroup.do" />',
                            waitTitle: '请等待',
                            waitMsg: '正在处理数据...',
                            params: {
		                   		 loginIds: loginIds	                    
		               			 },
                            timeout: 10,
                            success: function(form, action){
                                function ok(){
                                    groupStore.reload({callback: groupGridChangeAction});
                                    groupGridWindow.hide();
                                }
                                Ext.Msg.alert('提示', '操作成功。', ok);
                            }
                        });
                    }
                }
            },
            {
                text: '取消',
                handler: function(){
                    groupGridWindow.hide();
                    
                }
            }
        ]
    });
    
     var groupGridWindow = new Ext.Window({
     	width: 700,
        height: 500,
        title: '用户组',
        modal: true,
     	layout: 'border',
     	plain: true,
        bodyStyle: 'padding:5px;',
        buttonAlign: 'center',
        border: false,
        items: [
            {
                region: 'north',
                height: 230,
                layout: 'fit',
                items: groupForm
            },
            {
                region: 'center',
                layout: 'fit',
                items: groupUserGrid
            }
        ],
        closeAction: 'hide'
    });
    
    
    // --------------- viewport --------------------

    var viewport = new Ext.Viewport({
        layout: 'fit',
        border: false,    
        items: [{
                layout: 'form',
                items: [
                		
                    detailForm,
					{
                                layout: 'column',
                                items: [
                                        {
                                            columnWidth: .2,                                            
                                            items: groupGrid                                          
                                        },
                                        {
                                            columnWidth: .8,                                           
                                            items: userGrid                                           
                                        }]}
                ]}]
    });

    // --------------- init --------------------

    // bind event
    grid.getSelectionModel().addListener(
        'selectionchange',
        gridUpdateAction
    );
    
    // bind event
    userGrid.getSelectionModel().addListener(
        'selectionchange',
        userGridUpdateAction
    );

    detailForm.getForm().load({
         url: '<c:url value="/sms/getUserName.do"/>',
         waitMsg: 'loading...',
         success: function(aResponse, aOptions){
         },
         failure: function() {
             Ext.Msg.alert('提示', '请先登录！');                             
         }
     });
     groupStoreLoad();
     
    groupGrid.getSelectionModel().addListener(
        'selectionchange',
        groupGridChangeAction
    );
});
</script>
<%@ include file="/WEB-INF/views/common/footer.jsp"%>
